package com.zzr.demo.redis.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zzr.demo.redis.model.Person;
import com.zzr.demo.redis.service.CacheService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: xiaomi
 * @date: 2021/10/7
 * @description:
 */
@Service
public class PersonCacheServiceImpl implements CacheService<Person> {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Person get(String keyName) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String str = valueOperations.get(keyName);
        Person t = JSON.parseObject(str, new TypeReference<Person>() {
        });
        return t;
    }

    @Override
    public void set(Person model) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set(generateKey(model), JSON.toJSONString(model));
    }

    @Override
    public boolean update(String key, Person model) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String res = opsForValue.getAndSet(key, JSON.toJSONString(model));
        return res != null;
    }

    /**
     * 返回主键
     * 根据 redis key 的命名规范：
     * model 名称 + 分隔符‘::’ + model 的 id
     *
     * @param person
     * @return
     */
    private String generateKey(Person person) {
        return "person::" + person.getId();
    }
}
